<template>
  <div>
    <div style="padding: 0 0 10px 16px; display: flex; flex-direction: row; justify-content: flex-start">
      <div style="width: 2px; height: 16px; border: 2px solid #724eff; margin-right: 11px"></div>
      <div style="margin: 0 20px 0 0; font-weight: 700; color: #606266">汇报线梳理</div>
      <el-form label-position="right" size="small" inline>
        <el-form-item label="结构描述">
          <el-input
            v-model="sodData.structureDescription"
            type="textarea"
            maxlength="128"
            show-word-limit
            style="width: 220px"></el-input>
        </el-form-item>
        <el-form-item label="汇报线清晰度评价">
          <el-input
            v-model="sodData.reportClarityEvaluation"
            type="textarea"
            maxlength="128"
            show-word-limit
            style="width: 220px"></el-input>
        </el-form-item>
        <el-form-item label="汇报线执行力评价">
          <el-input
            v-model="sodData.reportExecutionEvaluation"
            type="textarea"
            maxlength="128"
            show-word-limit
            style="width: 220px"></el-input>
        </el-form-item>
      </el-form>
      <div>
        <el-button v-if="isUpdating" type="primary" size="mini" disabled icon="el-icon-loading">保存汇报线</el-button>
        <el-button v-else type="primary" size="mini" plain @click.stop="handleSaveStructure">保存汇报线</el-button>
      </div>
    </div>
    <div style="padding: 0 0 10px 16px; display: flex; flex-direction: row; justify-content: flex-start">
      <div style="width: 2px; height: 16px; border: 2px solid #724eff; margin-right: 11px"></div>
      <div style="font-weight: 700; color: #606266">人力数据</div>
      <div v-if="!isCurStaff">
        <el-alert
          :title="'这是上一次复盘录入的人力数据, 请在此基础上修改(如删除离职的)'"
          type="warning"
          :closable="false"
          show-icon></el-alert>
      </div>
    </div>
    <el-table
      ref="refTable"
      v-loading="isFetching"
      :data="tableData"
      element-loading-text="Loading"
      fit
      style="width: 100%"
      @cell-dblclick="handleCellDblclick">
      <el-table-column fixed type="expand">
        <template slot-scope="{ row }">
          <el-form
            :ref="`diagnose5_form${row.__fid}`"
            :model="row"
            :rules="rules"
            label-position="right"
            label-width="150px"
            size="small"
            class="table_expand">
            <div style="width: 90%; display: flex; flex-direction: row; justify-content: flex-start; gap: 50px">
              <div>
                <el-form-item label="姓名" :rules="rules.staffName">
                  <el-input
                    v-model="row.staffName"
                    placeholder="重复的姓名, 加数字以区分"
                    :disabled="row.id && row.id > 0"
                    style="width: 180px"></el-input>
                </el-form-item>
                <el-form-item label="性别" :rules="rules.staffSex">
                  <el-select v-model="row.staffSex" style="width: 180px">
                    <el-option label="男" :value="0"></el-option>
                    <el-option label="女" :value="1"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="性格类型">
                  <el-input v-model="row.characterType" disabled style="width: 180px"></el-input>
                </el-form-item>
                <el-form-item label="在职状态" :rules="rules.employmentStatus">
                  <el-select v-model="row.employmentStatus" style="width: 180px">
                    <el-option
                      v-for="item in baseEnums.incumbencyStatus"
                      :key="item.code"
                      :label="item.name"
                      :value="item.code"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="核心定位" :rules="rules.corePosition">
                  <el-select v-model="row.corePosition" style="width: 180px">
                    <el-option
                      v-for="item in baseEnums.centralPositioning"
                      :key="item.code"
                      :label="item.name"
                      :value="item.code"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="核心职能(可多选)" :rules="rules.coreFunction">
                  <el-select v-model="row.coreFunction" multiple style="width: 180px">
                    <el-option
                      v-for="item in baseEnums.functionality"
                      :key="item.code"
                      :label="item.name"
                      :value="item.code"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="其他职能(可多选)" :rules="rules.otherFunctions">
                  <el-select v-model="row.otherFunctions" multiple style="width: 180px">
                    <el-option
                      v-for="item in baseEnums.functionality"
                      :key="item.code"
                      :label="item.name"
                      :value="item.code"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="岗位名称">
                  <el-input v-model="row.jobTitle" style="width: 180px" placeholder="请输入岗位名称"></el-input>
                </el-form-item>
                <el-form-item label="备注">
                  <el-input
                    v-model="row.memo"
                    type="textarea"
                    maxlength="128"
                    show-word-limit
                    style="width: 180px"></el-input>
                </el-form-item>
                <!--操作-->
                <el-form-item>
                  <el-button v-if="isUpdating" type="primary" disabled icon="el-icon-loading" style="width: 120px">
                    提交中
                  </el-button>
                  <el-button
                    v-else-if="row.id === undefined"
                    type="primary"
                    @click="handleSubmitForm(`diagnose5_form${row.__fid}`, true, row)">
                    保存
                  </el-button>
                  <el-button v-else type="warning" @click="handleSubmitForm(`diagnose5_form${row.__fid}`, false, row)">
                    修改
                  </el-button>
                </el-form-item>
              </div>
              <div>
                <el-form-item label="公历生日" :rules="rules.birthDate">
                  <el-date-picker
                    v-model="row.birthDate"
                    type="date"
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"
                    placeholder="选择日期"
                    :picker-options="{ disabledDate: picDisabledDate }"
                    style="width: 180px"></el-date-picker>
                </el-form-item>
                <el-form-item label="入职年月">
                  <el-date-picker
                    v-model="row.hireDate"
                    type="month"
                    format="yyyy-MM"
                    value-format="yyyy-MM"
                    placeholder="选择月份"
                    :picker-options="{ disabledDate: picDisabledDate }"
                    style="width: 180px"></el-date-picker>
                </el-form-item>
                <el-form-item label="在职时长">
                  <el-input v-model="row.employmentDuration" disabled style="width: 180px"></el-input>
                </el-form-item>
                <el-form-item label="成果主观评级" :rules="rules.achievementRating">
                  <div class="star_level">
                    <el-rate v-model="row.achievementRating" :max="3"></el-rate>
                    <el-button type="info" size="mini" plain @click.stop="() => (row.achievementRating = 0)">
                      清除
                    </el-button>
                  </div>
                </el-form-item>
                <el-form-item label="能力主观评级" :rules="rules.abilityRating">
                  <div class="star_level">
                    <el-rate v-model="row.abilityRating" :max="3"></el-rate>
                    <el-button type="info" size="mini" plain @click.stop="() => (row.abilityRating = 0)">
                      清除
                    </el-button>
                  </div>
                </el-form-item>
                <el-form-item label="态度主观评级" :rules="rules.attitudeRating">
                  <div class="star_level">
                    <el-rate v-model="row.attitudeRating" :max="3"></el-rate>
                    <el-button type="info" size="mini" plain @click.stop="() => (row.attitudeRating = 0)">
                      清除
                    </el-button>
                  </div>
                </el-form-item>
                <el-form-item label="对团队满意度" :rules="rules.teamSatisfaction">
                  <div class="star_level">
                    <el-rate v-model="row.teamSatisfaction" :max="3"></el-rate>
                    <el-button type="info" size="mini" plain @click.stop="() => (row.teamSatisfaction = 0)">
                      清除
                    </el-button>
                  </div>
                </el-form-item>
                <el-form-item label="对团队不满意的地方">
                  <el-input
                    v-model="row.teamDissatisfaction"
                    type="textarea"
                    maxlength="128"
                    show-word-limit
                    style="width: 180px"></el-input>
                </el-form-item>
                <el-form-item label="信息来源">
                  <el-input
                    v-model="row.infoSource"
                    type="textarea"
                    maxlength="128"
                    show-word-limit
                    style="width: 180px"></el-input>
                </el-form-item>
              </div>
            </div>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column fixed prop="staffName" label="姓名" align="center" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column prop="staffSex" label="性别" align="center" width="60">
        <template slot-scope="{ row }">{{ row.staffSex == 1 ? '女' : '男' }}</template>
      </el-table-column>
      <el-table-column prop="characterType" label="性格" align="center" width="60">
        <template slot-scope="{ row }">{{ row.characterType ? `${row.characterType}型` : '' }}</template>
      </el-table-column>
      <el-table-column prop="employmentStatus" label="在职状态" align="center" width="90">
        <template slot-scope="{ row }">{{ row.employmentStatus | fltIncumbencyStatus }}</template>
      </el-table-column>
      <el-table-column prop="corePosition" label="核心定位" align="center" width="90">
        <template slot-scope="{ row }">{{ row.corePosition | fltCentralPositioning }}</template>
      </el-table-column>
      <el-table-column
        prop="jobTitle"
        label="岗位名称"
        align="center"
        width="90"
        show-overflow-tooltip></el-table-column>
      <el-table-column prop="birthDate" label="公历生日" align="center" width="100"></el-table-column>
      <el-table-column prop="hireDate" label="入职年月" align="center" width="80"></el-table-column>
      <el-table-column prop="employmentDuration" label="在职时长" align="center" width="80"></el-table-column>
      <el-table-column prop="achievementRating" label="成果主观评级" align="center" width="105">
        <template slot-scope="{ row }">
          <el-rate v-model="row.achievementRating" :max="3" disabled></el-rate>
        </template>
      </el-table-column>
      <el-table-column prop="abilityRating" label="能力主观评级" align="center" width="105">
        <template slot-scope="{ row }">
          <el-rate v-model="row.abilityRating" :max="3" disabled></el-rate>
        </template>
      </el-table-column>
      <el-table-column prop="attitudeRating" label="态度主观评级" align="center" width="105">
        <template slot-scope="{ row }">
          <el-rate v-model="row.attitudeRating" :max="3" disabled></el-rate>
        </template>
      </el-table-column>
      <el-table-column prop="teamSatisfaction" label="团队满意度" align="center" width="105">
        <template slot-scope="{ row }">
          <el-rate v-model="row.teamSatisfaction" :max="3" disabled></el-rate>
        </template>
      </el-table-column>
      <el-table-column
        prop="teamDissatisfaction"
        label="不满意的地方"
        align="center"
        width="120"
        show-overflow-tooltip></el-table-column>
      <el-table-column prop="memo" label="备注" align="center" width="120" show-overflow-tooltip></el-table-column>
      <el-table-column prop="createDate" label="创建日期" align="center" width="120">
        <template slot-scope="{ row }">{{ row.createDate ? row.createDate.substring(0, 11) : '--' }}</template>
      </el-table-column>
      <el-table-column fixed="right" align="center" width="180">
        <template slot="header">
          <el-button type="primary" size="mini" plain @click.stop="handleAddEmptyRow">添加一行</el-button>
        </template>
        <template slot-scope="{ row }">
          <span v-if="pop.zxd.isFetching">
            <i class="el-icon-loading"></i>
            生成中...
          </span>
          <el-link
            v-if="row.id && row.id > 0 && !pop.zxd.isFetching"
            type="success"
            style="margin-right: 5px"
            @click.stop.native="handleOpenZiXunDan(row)">
            参考咨询单
          </el-link>
          <el-button v-if="row.id && row.id > 0" type="danger" size="mini" plain @click.stop="handleDelete(row)">
            删除
          </el-button>
          <el-button v-else type="warning" size="mini" plain @click.stop="handleDeleteRow(row)">移除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 查看咨询单 -->
    <el-drawer :visible.sync="pop.zxd.showMe" :with-header="false" direction="rtl" width="30%">
      <div class="facial_model">
        <i v-if="pop.zxd.isFetching" class="el-icon-loading"></i>
        <img v-else :src.sync="pop.zxd.imgUrl" width="100%" />
      </div>
    </el-drawer>
  </div>
</template>

<script>
import * as apiSts from '@/api/_com_';
// 引入后端 API
import {
  delStaffDiagnoseById,
  getStaffDiagnoseByNo,
  getStaffDiagnoseZxd,
  getStaffEnums,
  saveStaffDiagnoseByNo,
  saveStaffDiagnoseOrg,
} from '@/api/diagnose';
// 引入自定义组件
import '@/utils/datefmt';
// 引入第三方组件
import { MessageBox } from 'element-ui';
import { mapGetters } from 'vuex';

const EmptyStaffData = {
  id: undefined,
  diagnoseNo: '',
  staffName: '', // 非空
  staffSex: 0, // 0: 男, 1: 女, 非空
  characterType: '',
  employmentStatus: undefined, // 非空
  corePosition: undefined, // 非空
  coreFunction: [], // 非空
  otherFunctions: [],
  jobTitle: '',
  birthDate: '', // 非空
  hireDate: '',
  employmentDuration: undefined,
  staffPhoto: '',
  adviceSheetVersion: 1,
  achievementRating: 0, // 非空
  abilityRating: 0, // 非空
  attitudeRating: 0, // 非空
  teamSatisfaction: 0, // 非空
  teamDissatisfaction: '',
  infoSource: '',
  memo: '',
  coachId: 0,
  coachName: '',
  __fid: '', // Form 表单ID
};

const DefaultSodData = {
  id: undefined,
  structureDescription: '',
  reportClarityEvaluation: '',
  reportExecutionEvaluation: '',
};

const EnumIncumbencyStatus = [];
const EnumCentralPositioning = [];

export default {
  name: 'Diagnose5',
  filters: {
    fltIncumbencyStatus(val) {
      const tmp = EnumIncumbencyStatus.find(x => x.code == val);
      if (tmp) {
        return tmp.name;
      }
      return '';
    },
    fltCentralPositioning(val) {
      const tmp = EnumCentralPositioning.find(x => x.code == val);
      if (tmp) {
        return tmp.name;
      }
      return '';
    },
  },
  data() {
    return {
      baseEnums: {},
      tableData: [],
      sodData: DefaultSodData,
      salon: {},
      rules: {
        staffName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        staffSex: [{ required: true, message: '请选择性别', trigger: 'blur' }],
        employmentStatus: [{ required: true, message: '请选择在职状态', trigger: 'blur' }],
        corePosition: [{ required: true, message: '请选择核心定位', trigger: 'blur' }],
        coreFunction: [{ required: true, type: 'array', min: 1, message: '请选择至少一个核心职能', trigger: 'blur' }],
        birthDate: [{ required: true, message: '请选择公历生日', trigger: 'blur' }],
      },
      pop: {
        zxd: {
          showMe: false,
          imgUrl: '',
          isFetching: false,
        },
      },
      isFetching: false, // 通用的&互斥的, 加载后端数据
      isUpdating: false,
      isCurStaff: true, // 是否为当期的员工信息，如果是往期的，则提示修改
      curEditCell: undefined, // 当前编辑的单元格: 主键id + "_" + 单元格属性名(prop)
    };
  },
  computed: {
    ...mapGetters(['deptId', 'openId', 'id', 'name']),
  },
  created() {
    this.loadStaffEnums();
  },
  methods: {
    loadStaffEnums: async function () {
      const errAlertMsg = '查询类型失败';
      getStaffEnums()
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              MessageBox.alert(res.data.message);
            } else {
              MessageBox.alert(errAlertMsg);
            }
            return;
          }
          const ret = res.data.data;
          if (ret) {
            this.baseEnums = Object.assign({}, ret);
            EnumIncumbencyStatus.push(...ret.incumbencyStatus);
            EnumCentralPositioning.push(...ret.centralPositioning);
          }
        })
        .catch(err => {
          console.log('getStaffEnums', err);
          MessageBox.alert(errAlertMsg);
        });
    },
    loadDiagnoseData: async function (salon /* {salonId: '', salonNo: '', salonName: '', diagnoseNo: ''} */) {
      if (!salon || !salon.diagnoseNo) {
        return;
      }
      this.salon = Object.assign({}, salon);
      this.loadDiagnose5();
    },
    loadDiagnose5: async function () {
      if (this.isFetching) {
        return;
      }
      this.isFetching = true;
      this.sodData = Object.assign({}, DefaultSodData);
      this.tableData.splice(0, this.tableData.length);
      const errAlertMsg = '查询人力复盘信息失败';
      await getStaffDiagnoseByNo(this.salon.salonId, this.salon.diagnoseNo)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              MessageBox.alert(res.data.message);
            } else {
              MessageBox.alert(errAlertMsg);
            }
            return;
          }
          const ret = res.data.data;
          if (ret) {
            this.isCurStaff = ret.diagnoseNo && ret.diagnoseNo === this.salon.diagnoseNo;
            if (ret.sod) {
              this.sodData = Object.assign({}, ret.sod);
            }
            if (ret.ssdList && ret.ssdList.length > 0) {
              ret.ssdList.forEach(x => {
                x.__fid = this.getRadomStr6();
                this.tableData.push(x);
              });
            }
          }
        })
        .catch(err => {
          console.log('getStaffDiagnoseByNo', err);
          MessageBox.alert(errAlertMsg);
        })
        .finally(() => {
          this.isFetching = false;
        });
    },
    handleCellDblclick: async function (row, column, cell, event) {
      const target = event.target || event.srcElement;
      const nodeName = target.nodeName;
      if (!row || !column || !cell || nodeName !== 'DIV') {
        return;
      }
      // this.curEditCell = `${row.id}_${column.property}`;
      // console.log('curEditCell', this.curEditCell);
    },
    handleSaveStructure: async function () {
      if (this.isUpdating) {
        return;
      }
      this.isUpdating = true;
      if (!this.sodData.id) {
        this.sodData.id = null;
      }
      const errAlertMsg = '保存汇报线梳理信息失败';
      saveStaffDiagnoseOrg(this.salon.diagnoseNo, this.sodData)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              MessageBox.alert(res.data.message);
            } else {
              MessageBox.alert(errAlertMsg);
            }
            return;
          }
          MessageBox.alert('保存成功');
        })
        .catch(err => {
          console.log('saveStaffDiagnoseOrg', err);
          MessageBox.alert(errAlertMsg);
        })
        .finally(() => {
          this.isUpdating = false;
        });
    },
    handleOpenZiXunDan: async function (row) {
      if (this.pop.zxd.isFetching) {
        return;
      }
      this.pop.zxd.isFetching = true;
      this.pop.zxd.imgUrl = '';
      const errAlertMsg = '生成咨询单图片失败';
      getStaffDiagnoseZxd(this.salon.salonId, row.id)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              MessageBox.alert(res.data.message);
            } else {
              MessageBox.alert(errAlertMsg);
            }
            this.pop.zxd.showMe = false;
            return;
          }
          this.pop.zxd.imgUrl = res.data.data;
          this.pop.zxd.showMe = true;
        })
        .catch(err => {
          console.log('delStaffDiagnoseById', err);
          this.pop.zxd.showMe = false;
          MessageBox.alert(errAlertMsg);
        })
        .finally(() => {
          this.pop.zxd.isFetching = false;
        });
    },
    handleAddEmptyRow: async function () {
      const cpy = Object.assign({}, EmptyStaffData);
      cpy.coachName = this.name;
      cpy.__fid = this.getRadomStr6();
      this.tableData.push(cpy);
    },
    handleDelete: async function (row) {
      const errAlertMsg = '删除人力复盘信息失败';
      delStaffDiagnoseById(row.id)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              MessageBox.alert(res.data.message);
            } else {
              MessageBox.alert(errAlertMsg);
            }
            return;
          }
          this.handleDeleteRow(row);
        })
        .catch(err => {
          console.log('delStaffDiagnoseById', err);
          MessageBox.alert(errAlertMsg);
        });
    },
    handleDeleteRow: async function (row) {
      // 根据 index 从 this.tableData 中将数据删除
      const index = this.tableData.indexOf(row);
      if (index !== -1) {
        this.tableData.splice(index, 1);
      }
    },
    picDisabledDate(date) {
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      return !(date - today < 0);
    },
    getRadomStr6() {
      // 生成长度为 6 的随机字符串
      const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
      let result = '';
      for (let i = 0; i < 6; i++) {
        result += chars.charAt(Math.floor(Math.random() * chars.length));
      }
      return result;
    },
    calEmploymentDuration(dateStr) {
      // 根据选中的月份 yyyy-MM, 自动计算距今天的月份数，不足1月的，计算天数
      const hireDate = new Date(dateStr);
      const today = new Date();
      const years = today.getFullYear() - hireDate.getFullYear();
      const months = today.getMonth() - hireDate.getMonth();
      const days = today.getDate() - hireDate.getDate();
      let totalMonths = years * 12 + months;
      if (days < 0) {
        totalMonths -= 1;
      }
      const totalDays = Math.floor((today - hireDate) / (1000 * 60 * 60 * 24));
      return totalMonths > 0 ? `${totalMonths}月` : `${totalDays}天`;
    },
    handleSubmitForm: async function (formName, isadd, row) {
      // Validate row data against rules
      for (const key in this.rules) {
        if (this.rules.hasOwnProperty(key)) {
          if (key === 'staffSex') {
            continue;
          }
          const rule = this.rules[key][0];
          if (rule.required && !row[key]) {
            MessageBox.alert(rule.message);
            return;
          }
          if (rule.type === 'array' && row[key].length < rule.min) {
            MessageBox.alert(rule.message);
            return;
          }
          if (rule.type === 'number' && typeof row[key] !== 'number') {
            MessageBox.alert(rule.message);
            return;
          }
        }
      }

      if (isadd) {
        // 检查 tableData 中有没有重复的 staffName
        const staffNames = this.tableData.map(item => item.staffName);
        const hasDuplicates = staffNames.some((item, index) => staffNames.indexOf(item) !== index);
        if (hasDuplicates) {
          MessageBox.alert('存在重复的姓名，同名员工请在姓名后面添加数字加以区别');
          return;
        }
      }

      if (row.id <= 0) {
        row.id = null;
      }
      if (row.hireDate) {
        row.employmentDuration = this.calEmploymentDuration(row.hireDate);
      }

      this.isUpdating = true;
      const errAlertMsg = '保存人力复盘信息失败';
      saveStaffDiagnoseByNo(this.salon.salonId, this.salon.diagnoseNo, row)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              MessageBox.alert(res.data.message);
            } else {
              MessageBox.alert(errAlertMsg);
            }
            return;
          }
          this.loadDiagnose5();
          MessageBox.alert('保存成功');
        })
        .catch(err => {
          console.log('saveStaffDiagnoseByNo', err);
          MessageBox.alert(errAlertMsg);
        })
        .finally(() => {
          this.isUpdating = false;
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.table_expand {
  padding: 5px 16px;
  font-size: 0;
  background-color: rgb(249, 243, 234);

  .star_level {
    width: 180px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-start;
    gap: 10px;
  }
}
.table_expand label {
  width: 90px;
  color: #99a9bf;
}
.table_expand .el-form-item {
  margin-right: 0;
  margin-bottom: 5px;
  width: 50%;
}

.facial_model {
  width: 40vw;
  height: 100vh;
  position: fixed;
  top: 0;
  right: 1vw;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  background-color: #ffffff;
}
</style>
